/*
 * Name: Minh-Tuan ta
 * abstract: Keeps common used methods
 */

package utils;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import beans.*;

public class Utils {
	public static boolean isLoggedIn(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		boolean result = false;
		
		if (session.getAttribute("User") != null)
			result = true;
		
		return result;
	}
	
	public static String doUpload(HttpServletRequest request,String webContext)
	{
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("User");
		String uploadLocation= webContext + File.separator + "images" + File.separator + "users" + File.separator;
		File fullFile = new File("");
		File savedFile = new File("");
		
		
		
		try{
			//*****(1) Create a factory for disk-based file items *******
			FileItemFactory factory = new DiskFileItemFactory();

			//*****(2) Create a new file upload handler ******
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			//*****(3) Parse the HTTP Request Stream *********
			List<FileItem> items =  (List<FileItem>) upload.parseRequest(request);
			for(int index=0;index<items.size();index++){
				FileItem item = (FileItem) items.get(index);
				
				if (item.isFormField())
				{
					String name = item.getFieldName();
				    String value = item.getString();
				    if(name.equals("albumID")){
				    	request.setAttribute("albumID", value);
				    }
				}
				else
				{
					//if the uploadLocation doesn't exist, create one
					File dir = new File(uploadLocation + File.separator);
					
					if (dir.exists() == false) //not exist
					{
						//make the directory
						if (dir.mkdir() == false) //if fail to make the directory
							return null;
					}
					
					fullFile  = new File(item.getName());
					savedFile = new File(uploadLocation,fullFile.getName());
					item.write(savedFile);
				}
			}
		}catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return savedFile.getName();					
	}
}
